import React, { useMemo, useState } from 'react';
import {
  Card,
  Form,
  Input,
  Button,
  Table,
  Space,
  Modal,
  DatePicker,
  Image,
  Select,
  Switch,
  InputNumber,
  message,
} from 'antd';
import {
  CalendarOutlined,
  QrcodeOutlined,
  PlusOutlined,
  EditOutlined,
  DeleteOutlined,
} from '@ant-design/icons';

const { RangePicker } = DatePicker;
const { Option } = Select;

export default function TempUserActivity() {
  const [searchForm] = Form.useForm();
  const [newForm] = Form.useForm();
  const [editForm] = Form.useForm();

  const [data, setData] = useState(() => (
    Array.from({ length: 8 }).map((_, i) => ({
      id: i + 1,
      name: `临时活动-${i + 1}`,
      photoQrCode: `https://api.qrserver.com/v1/create-qr-code/?size=120x120&data=TEMP-${i + 1}`,
      photoPassword: i % 2 === 0 ? '123456' : '',
      printNum: Math.floor(Math.random() * 50),
      photoNum: Math.floor(Math.random() * 120),
      uploadSwitch: i % 2 === 0,
      cloudPhotoSwitch: i % 3 === 0,
      electronicSwitch: i % 2 === 1,
      electronicPrice: Math.floor(Math.random() * 20),
      createBy: i % 2 === 0 ? 'admin' : 'operator',
      createTime: `2025-01-${(i % 28) + 1} 12:00:00`,
    }))
  ));
  const [loading, setLoading] = useState(false);
  const [selectedRowKeys, setSelectedRowKeys] = useState([]);

  const [newOpen, setNewOpen] = useState(false);
  const [editOpen, setEditOpen] = useState(false);
  const [albumOpen, setAlbumOpen] = useState(false);
  const [currentRow, setCurrentRow] = useState(null);

  const [machineOptions] = useState([
    { id: 1, name: '设备A' },
    { id: 2, name: '设备B' },
    { id: 3, name: '设备C' },
  ]);

  const columns = useMemo(() => ([
    { title: 'ID', dataIndex: 'id', width: 70 },
    { title: '活动名称', dataIndex: 'name', width: 140 },
    {
      title: '活动二维码', dataIndex: 'photoQrCode', width: 120,
      render: (url) => <Image src={url} width={60} height={60} style={{ objectFit: 'contain' }} />,
    },
    { title: '相册密码', dataIndex: 'photoPassword', width: 100 },
    { title: '打印数量', dataIndex: 'printNum', width: 100 },
    { title: '照片数量', dataIndex: 'photoNum', width: 100 },
    { title: '上传开关', dataIndex: 'uploadSwitch', width: 100, render: (v) => (v ? '开启' : '关闭') },
    { title: '云相册', dataIndex: 'cloudPhotoSwitch', width: 100, render: (v) => (v ? '开启' : '关闭') },
    { title: '电子照', dataIndex: 'electronicSwitch', width: 100, render: (v) => (v ? '开启' : '关闭') },
    { title: '电子照价格', dataIndex: 'electronicPrice', width: 110, render: (v) => `${v} 元` },
    { title: '创建者', dataIndex: 'createBy', width: 100 },
    { title: '创建时间', dataIndex: 'createTime', width: 160 },
    {
      title: '操作', dataIndex: 'actions', fixed: 'right', align: 'right', width: 200,
      render: (_, row) => (
        <Space>
          <Button size="small" icon={<QrcodeOutlined />} onClick={() => { setCurrentRow(row); setAlbumOpen(true); }}>相册</Button>
          <Button size="small" icon={<EditOutlined />} onClick={() => handleEdit(row)}>编辑</Button>
          <Button size="small" danger icon={<DeleteOutlined />} onClick={() => handleDelete(row)}>删除</Button>
        </Space>
      )
    },
  ]), []);

  const handleSearch = async () => {
    const values = await searchForm.validateFields().catch(() => null);
    if (!values) return;
    setLoading(true);
    setTimeout(() => {
      setData(prev => prev.filter(item => {
        const byCreateBy = values.createBy ? item.createBy.includes(values.createBy) : true;
        const byName = values.activityName ? item.name.includes(values.activityName) : true;
        const byId = values.id ? String(item.id).includes(values.id) : true;
        return byCreateBy && byName && byId;
      }));
      setLoading(false);
    }, 300);
  };

  const resetSearch = () => {
    searchForm.resetFields();
    setData(Array.from({ length: 8 }).map((_, i) => ({
      id: i + 1,
      name: `临时活动-${i + 1}`,
      photoQrCode: `https://api.qrserver.com/v1/create-qr-code/?size=120x120&data=TEMP-${i + 1}`,
      photoPassword: i % 2 === 0 ? '123456' : '',
      printNum: Math.floor(Math.random() * 50),
      photoNum: Math.floor(Math.random() * 120),
      uploadSwitch: i % 2 === 0,
      cloudPhotoSwitch: i % 3 === 0,
      electronicSwitch: i % 2 === 1,
      electronicPrice: Math.floor(Math.random() * 20),
      createBy: i % 2 === 0 ? 'admin' : 'operator',
      createTime: `2025-01-${(i % 28) + 1} 12:00:00`,
    })));
  };

  const rowSelection = {
    selectedRowKeys,
    onChange: setSelectedRowKeys,
  };

  const handleDelete = (row) => {
    Modal.confirm({
      title: '删除临时活动',
      content: `将删除临时活动 ${row.name}（ID: ${row.id}）`,
      onOk: () => {
        setData(prev => prev.filter(d => d.id !== row.id));
        message.success('删除成功');
      },
    });
  };

  const handleEdit = (row) => {
    setCurrentRow(row);
    editForm.setFieldsValue({
      name: row.name,
      photoPassword: row.photoPassword,
      electronicPrice: row.electronicPrice,
    });
    setEditOpen(true);
  };

  return (
    <div style={{ padding: 16 }}>
      <Card
        title={<Space><CalendarOutlined />临时用户活动</Space>}
        extra={(
          <Space>
            <Button type="primary" icon={<PlusOutlined />} onClick={() => setNewOpen(true)}>新增活动</Button>
          </Space>
        )}
        style={{ marginBottom: 16 }}
      >
        <Form layout="inline" form={searchForm} style={{ rowGap: 12 }}>
          <Form.Item name="createBy" label="创建者">
            <Input placeholder="创建者" allowClear style={{ width: 160 }} />
          </Form.Item>
          <Form.Item name="activityName" label="活动名称">
            <Input placeholder="活动名称" allowClear style={{ width: 180 }} />
          </Form.Item>
          <Form.Item name="id" label="ID">
            <Input placeholder="活动ID" allowClear style={{ width: 140 }} />
          </Form.Item>
          <Form.Item name="dateRangeActivity" label="活动时间">
            <RangePicker showTime />
          </Form.Item>
          <Form.Item name="dateRangeCreate" label="创建时间">
            <RangePicker showTime />
          </Form.Item>
          <Form.Item>
            <Space>
              <Button type="primary" onClick={handleSearch}>查询</Button>
              <Button onClick={resetSearch}>重置</Button>
            </Space>
          </Form.Item>
        </Form>
      </Card>

      <Card>
        <Table
          rowKey="id"
          columns={columns}
          dataSource={data}
          loading={loading}
          rowSelection={rowSelection}
          pagination={{ pageSize: 10 }}
          size="small"
        />
      </Card>

      {/* 新增活动 */}
      <Modal
        title="新增临时活动"
        open={newOpen}
        onCancel={() => setNewOpen(false)}
        onOk={async () => {
          const values = await newForm.validateFields().catch(() => null);
          if (!values) return;
          const newId = data.length ? Math.max(...data.map(d => d.id)) + 1 : 1;
          setData(prev => [{
            id: newId,
            name: values.name || `临时活动-${newId}`,
            photoQrCode: `https://api.qrserver.com/v1/create-qr-code/?size=120x120&data=TEMP-${newId}`,
            photoPassword: values.photoPassword || '',
            printNum: 0,
            photoNum: 0,
            uploadSwitch: !!values.uploadSwitch,
            cloudPhotoSwitch: !!values.cloudPhotoSwitch,
            electronicSwitch: !!values.electronicSwitch,
            electronicPrice: values.electronicPrice || 0,
            createBy: 'admin',
            createTime: new Date().toISOString().slice(0, 19).replace('T', ' '),
          }, ...prev]);
          setNewOpen(false);
          newForm.resetFields();
          message.success('新增活动成功');
        }}
        destroyOnHidden
        width={760}
      >
        <Form form={newForm} layout="vertical">
          <Form.Item name="name" label="活动名称">
            <Input placeholder="活动名称" style={{ width: 300 }} />
          </Form.Item>
          <Form.Item name="dateRange" label="活动时间">
            <RangePicker showTime />
          </Form.Item>
          <Form.Item name="machines" label="选择设备">
            <Select placeholder="选择设备(多选)" mode="multiple" style={{ width: 360 }}>
              {machineOptions.map(m => (<Option key={m.id} value={String(m.id)}>{m.name}</Option>))}
            </Select>
          </Form.Item>
          <Form.Item name="photoPassword" label="相册密码">
            <Input type="password" placeholder="相册密码" style={{ width: 220 }} />
          </Form.Item>
          <Space>
            <Form.Item name="uploadSwitch" label="上传开关" valuePropName="checked">
              <Switch defaultChecked />
            </Form.Item>
            <Form.Item name="cloudPhotoSwitch" label="云相册" valuePropName="checked">
              <Switch defaultChecked />
            </Form.Item>
            <Form.Item name="electronicSwitch" label="电子照" valuePropName="checked">
              <Switch />
            </Form.Item>
          </Space>
          <Form.Item name="electronicPrice" label="电子照价格">
            <InputNumber min={0} style={{ width: 200 }} />
          </Form.Item>
        </Form>
      </Modal>

      {/* 编辑活动（简版） */}
      <Modal
        title="编辑临时活动"
        open={editOpen}
        onCancel={() => setEditOpen(false)}
        onOk={async () => {
          const values = await editForm.validateFields().catch(() => null);
          if (!values || !currentRow) return;
          setData(prev => prev.map(d => (d.id === currentRow.id ? {
            ...d,
            name: values.name ?? d.name,
            photoPassword: values.photoPassword ?? d.photoPassword,
            electronicPrice: values.electronicPrice ?? d.electronicPrice,
          } : d)));
          message.success('保存成功');
          setEditOpen(false);
        }}
        destroyOnHidden
      >
        <Form form={editForm} layout="vertical">
          <Form.Item name="name" label="活动名称">
            <Input placeholder="活动名称" />
          </Form.Item>
          <Form.Item name="photoPassword" label="相册密码">
            <Input placeholder="相册密码" />
          </Form.Item>
          <Form.Item name="electronicPrice" label="电子照价格">
            <InputNumber min={0} />
          </Form.Item>
        </Form>
      </Modal>

      {/* 相册预览（简版） */}
      <Modal
        title="活动相册"
        open={albumOpen}
        onCancel={() => setAlbumOpen(false)}
        onOk={() => setAlbumOpen(false)}
        destroyOnHidden
        width={820}
      >
        <Space wrap>
          {Array.from({ length: 8 }).map((_, i) => (
            <Image key={i} src={`https://picsum.photos/seed/album_${i}/320/200`} width={320} height={200} style={{ objectFit: 'contain' }} />
          ))}
        </Space>
      </Modal>
    </div>
  );
}